﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using MediaBrowser.Library.Logging;


namespace MusicPluginProxy
{
    public static class AssemblyUtils
    {
        public static void RegisterAssemblyResolvers(string pluginFolder)
        {
            var baseDirectory = Path.Combine(pluginFolder, "MusicPlugin");

            Logger.ReportInfo("Adding assembly resolver " + baseDirectory);

            AppDomain.CurrentDomain.AssemblyResolve += AssemblyUtils.GetResolveEventHandlerForFolder(baseDirectory);
        }

        public static void ExtractResources(string pluginFolder)
        {
            try
            {
                Logger.ReportInfo("Creating new MusicPlugin directory");
                var baseDirectory = Path.Combine(pluginFolder, "MusicPlugin");
                if (!Directory.Exists(baseDirectory))
                    Directory.CreateDirectory(baseDirectory);

                string filename = Path.Combine(baseDirectory, "taglib-sharp.dll");

                if (!File.Exists(filename))
                    using (Stream theResource = new MemoryStream(Resources.taglib_sharp))
                    {
                        Logger.ReportInfo("Extracting " + filename);
                        ExtractResource(filename, theResource);
                    }

                filename = Path.Combine(baseDirectory, "MusicPlugin.dll");
                //if (!File.Exists(filename))
                    using (Stream theResource = new MemoryStream(Resources.MusicPlugin))
                    {
                        Logger.ReportInfo("Extracting " + filename);
                        ExtractResource(filename, theResource);
                    }

               //     filename = Path.Combine(baseDirectory, "MusicPlugin.ThemeModelItemInterfaces.dll");
               //// if (!File.Exists(filename))
               //     using (Stream theResource = new MemoryStream(Resources.MusicPlugin_ThemeModelItemInterfaces))
               //     {
               //         Logger.ReportInfo("Extracting " + filename);
               //         ExtractResource(filename, theResource);
               //     }
            }
            catch (Exception e)
            {
                Logger.ReportException("MusicPluginProxy cannot extract necessary resources", e);
            }
        }

        private static void ExtractResource(string filename, Stream theResource)
        {
            using (BinaryReader theReader = new BinaryReader(theResource))
            {
                using (FileStream theWriter = new FileStream(filename, FileMode.Create))
                {
                    byte[] theFileRead = new byte[theResource.Length];
                    theResource.Read(theFileRead, 0, theFileRead.Length);
                    theWriter.Write(theFileRead, 0, theFileRead.Length);
                }
            }
        }

        private static ResolveEventHandler GetResolveEventHandlerForFolder(string path)
        {
            return delegate(object sender, ResolveEventArgs args)
            {
                AssemblyName requiredAssemblyName = new AssemblyName(args.Name);
                string filePath = Path.Combine(path, requiredAssemblyName.Name + ".dll");
                if (File.Exists(filePath))
                {
                    Assembly assembly = Assembly.LoadFrom(filePath);
                    if ((assembly != null) && ((requiredAssemblyName.Version == null) || (assembly.GetName().Version == requiredAssemblyName.Version)))
                        return assembly;
                }
                return null;
            };
        }
    }
}
